﻿/**
 * 插入图片插件
 */
(function(E){
var Consts = E.consts, HdImage = 'HdImage', Event = E.mod('Event'),
	//static_url = (typeof STATIC_URL === 'string') ? STATIC_URL+'/js/jqeditor' : './js/jqeditor';
	//jqe_static_url全局变量，功外部修改
	static_url = typeof jqe_static_url === 'string' ? jqe_static_url : './';
	
Event.bind("oncomplete", function(){
	setTimeout(function(){
		resizeImageDivWidth();
	}, 500);
	
	setTimeout(function(){
		resizeImageDivWidth();
	}, 10000);
});

// 修正内容里面的图片外面div的width可能错误的问题
// 如图片宽300，但是div的width=80px
function resizeImageDivWidth( ){
	var div, config = E.plugin(HdImage).config;
	
	E.$('img').each(function(i, el){
		el.removeAttribute('height');
		el.removeAttribute('style');
		
		div = E.$(el).closest('div.img');
		// 如果图片的宽度大于
		if( el.width > config.max_width ){
			el.setAttribute('width', config.max_width);
		}
		
		if (div.size() ){
			if( el.width && el.width > 80 ){
				div.width(el.width);
				div.css('height', '');
			}
			div.find('strong').css('width', '');
		}
	});
}

E.plugin(HdImage, {
	inserthtml:'custom',
	
	config : {
		width:350,
		max_width : 600,
		position: 'center',
		overlay: true
	},
	//可供外部修改的配置信息
	settings : {
		//是否显示3列大小选项
		moreSize : true,
		maxUploadSize : '5M',
		//是否显示3列位置选项
		moreAlign : true,
		//上传图片按钮和添加url按钮被选中样式
		selectedClass : "selectedClass",
		//上传图片相关参数，默认使用小百科的
		img_src_action : 'baike_article_create.php',
		//图片描述是否可以为空
		discription_can_null : false,
		//获取上传input图片表单提交地址
		//[必须外部重写该方法]
		//[返回数据格式如{action:'www.abc.com', postParms:{name:'img'}}，
		//如果没有需要post提交的参数则可以直接返回string类型的url]
		getFileAction : function(){return alert('没有提供可调用的上传接口');},
		//获取上传url图片表单提交地址[必须外部重写该方法][参数同file]
		getUrlAction : function(){return alert('没有提供可调用的上传接口');}
	},
	//插件使用的一些静态属性配置
	staticAttr : {
		//file表单元素的name属性[该值不能修改,否则无法上传]
		inputFileName : "photofile",
		//url输入框
		inputUrlName : "img_url",
		//上传图片按钮name属性值
		uploadFileBtn : "uploadFileBtn", 
		//添加url按钮name属性值
		urlFileBtn : "urlFileBtn",
		//上传图片显示标签name属性值
		uploadShowName : "uploadShowName",
		//添加url图片显示标签属name性值
		urlShowName : "urlShowName",
		//图片大小单选按钮name属性值
		imgSizeName : "picWidthHeight",
		//图片显示方式单选按钮name属性值
		imgAlignName : "picAlign",
		//图片描述name属性值
		imgDiscription : "picAlt",
		//提交按钮name属性值
		uploadButton : "uploadButton",
		//上传功能单例运行
		uploadIsBusy : false 
	},
	style : '.jqe-plugin-HdImage{width:90%;margin:0 auto;}\
			.jqe-plugin-HdImage .input_tr{height:26px;}\
			.jqe-plugin-HdImage .first_span{left:15px;}\
			.jqe-plugin-HdImage .last_span{left:110px;}\
			.jqe-plugin-HdImage .uploadBoxTop{position:relative;border-bottom:1px solid #009AD9;height:29px;margin:0 0 3px;padding:0;}\
			.jqe-plugin-HdImage .uploadBoxTop span{position:absolute;top:0px;color:#666666;cursor:pointer;display:inline-block;line-height:25px;text-align:center;width:80px;border-left: 1px solid #FFFFFF;border-right: 1px solid #FFFFFF;border-top: 4px solid #FFFFFF;}\
			.jqe-plugin-HdImage .uploadBoxTop span.selectedClass{background-color:#FFFFFF;cursor:default;border-left: 1px solid #009AD9;border-right: 1px solid #009AD9;border-top: 4px solid #009AD9;border-bottom:2px solid #FFFFFF;color:#333333;}\
			.jqe-plugin-HdImage input,textarea{color:#111111;font-family:"lucida grande",taho,verdana,"trebuchet ms",sans-serif;font-size:12px;}\
			.jqe-plugin-HdImage .inputFile{height:22px;width:260px;border:1px solid #7F9DB9;}\
			.jqe-plugin-HdImage .inputUrl{height:18px;line-height:18px;width:260px;border:1px solid #7F9DB9;}\
			.jqe-plugin-HdImage .tips{color:#999999;line-height:22px;text-align:left;wodr-wrap:break-word;}\
			.jqe-plugin-HdImage .bgImg{height:61px;background:url("'+static_url+'/skins/bg/uploadimg_bg.gif") no-repeat scroll 0 0 transparent;margin:0 0 5px 10px;border:1px solid #999999;}\
			.jqe-plugin-HdImage .bgImg1{background-position:0 0px;width:70px;}\
			.jqe-plugin-HdImage .bgImg2{background-position:-72px -0px;width:68px;}\
			.jqe-plugin-HdImage .bgImg3{background-position:-142px 0;width:69px;}\
			.jqe-plugin-HdImage .alignImg{background:url("'+static_url+'/skins/bg/uploadimg_bg.gif") no-repeat scroll 0 0 transparent;margin:0 0 5px 10px;height:46px;border:1px solid #999999;}\
			.jqe-plugin-HdImage .alignImg1{background-position:0 -69px;width:70px}\
			.jqe-plugin-HdImage .alignImg2{background-position:-71px -69px;width:68px;}\
			.jqe-plugin-HdImage .alignImg3{background-position:-142px -69px;width:69px;}\
			.jqe-plugin-HdImage strong{line-height:22px;}',
	init : function() {
		var self = this,
			staticAttr = self.staticAttr,
			settings = self.settings,
			moreSize = settings.moreSize,
			moreAlign = settings.moreAlign,
			img_src_action = settings.img_src_action,
			discription_can_null = settings.discription_can_null;
		var html ='<table class="jqe-plugin-HdImage">'
			+ '<tr><td colspan="3"><div class="uploadBoxTop"><span name="'+staticAttr.uploadFileBtn+'" class="'+settings.selectedClass+' first_span">上传图片</span><span class="last_span" name="' + staticAttr.urlFileBtn + '">添加url</span></div></td></tr>'
			+ '<tr name="' + staticAttr.uploadShowName + '" class="input_tr"><td colspan="3">'
				+ '<input class="inputFile" type="file" name="' + staticAttr.inputFileName + '" size="35">'
				+ '<input type="hidden" value="'+img_src_action+'" name="img_src_action">'
			+ '</td></tr>'
			+ '<tr name="' + staticAttr.uploadShowName + '" class="input_tr"><td colspan="3"><label class="tips">图片格式：jpg、jpeg、png、gif，大小为'+settings.maxUploadSize+'以内</label></td></tr>'
			+ '<tr name="' + staticAttr.urlShowName + '" style="display:none;" class="input_tr"><td colspan="3"><input type="text" class="inputUrl" name="' + staticAttr.inputUrlName + '"></td></tr>'
			+ '<tr name="' + staticAttr.urlShowName + '" style="display:none;" class="input_tr"><td colspan="3"><label class="tips">注:请输入以jpg、jpeg、png、gif结束的url</label></td></tr>'
			+ '<tr><td height="30"><strong>图片大小：</strong></td><td></td><td></td></tr>';
		if(moreSize) {
			html += '<tr>'
				+ '<td><label><div class="bgImg bgImg1"></div><input type="radio" imgsize="_950" value="1" name="' + staticAttr.imgSizeName + '" checked="true">大(长边'+self.config.max_width+')</label></td>'
				+ '<td><label><div class="bgImg bgImg2"></div><input type="radio" imgsize="_s" value="1" name="' + staticAttr.imgSizeName + '">中(长边300)</label></td>'
				+ '<td><label><div class="bgImg bgImg3"></div><input type="radio" imgsize="_140" value="2" name="' + staticAttr.imgSizeName + '">小(长边140)</label></td>'
			+ '</tr>';
		}else {
			html += '<tr>'
					+ '<td colspan="3">'
						+ '<table width="100%;"><tr><td style="text-align:left;">'
							+ '<label><div class="bgImg bgImg1"></div><input type="radio" imgsize="_s" value="1" name="' + staticAttr.imgSizeName + '" checked="true">大(长边300px)</label>'
							+ '</td><td style="text-align:left;">'
							+ '<label><div class="bgImg bgImg3"></div><input type="radio" imgsize="_140" value="2" name="' + staticAttr.imgSizeName + '">小(长边140px)</label>'
						+ '</td></tr></table>'
					+ '</td>'
				+'</tr>';
		}
			html += '<tr><td height="30"><strong>对齐方式：</strong></td><td></td><td></td></tr>';
		if(moreAlign) {
			html += '<tr>'
				+ '<td><label><div class="alignImg alignImg1"></div><input type="radio" value="left" name="' + staticAttr.imgAlignName + '">图片居左</label></td>'
				+ '<td><label><div class="alignImg alignImg2"></div><input type="radio" value="center" name="' + staticAttr.imgAlignName + '" checked="true">图片居中</label></td>'
				+ '<td><label><div class="alignImg alignImg3"></div><input type="radio" value="right" name="' + staticAttr.imgAlignName + '">图片居右</label></td>'
			+ '</tr>';
		}else{
			html += '<tr>'
				+ '<td colspan="3">'
					+ '<table width="100%"><tr><td style="text-align:left;">'
						+ '<label><div class="alignImg alignImg1"></div><input type="radio" value="left" name="' + staticAttr.imgAlignName + '" >图片居左</label>'
						+ '</td><td style="text-align:left;">'
						+ '<label><div class="alignImg alignImg3"></div><input type="radio" value="right" name="' + staticAttr.imgAlignName + '" checked="true">图片居右</label>'
					+ '</td></tr></table>'
				+ '</td>'
			+ '</tr>';
		}
		html += '<tr><td colspan="3" height="30"><strong>图片描述';
		if(!discription_can_null){
			html += '[<font color="red">必填</font>]';
		}
		html += '：</strong></td><td></td><td></td></tr>'
		+ '<tr><td colspan="3"><textarea style="width:95%;height:30px;" maxlength="100" name="' + staticAttr.imgDiscription + '"></textarea></td></tr>'
		+ '</table>';
		self.cache['html'] = html;
	},
	/*
		额外绑定事件
		target : 事件源 jquery对象
		panel : 面板
		self ： 插件本身
	*/
	action : function( target, panel, self ) {
		var fun = target.attr("name");
		if(typeof self[fun] === Consts.typeof_function) {
			return self[fun](target, panel, self);
		}
	},
	callback : function( panel, self ) {
		var staticAttr = self.staticAttr;
		panel.find(":submit").replaceWith("<input type='button' value=' 提 交 ' name='" + staticAttr.uploadButton + "'>");
	},
	/*
		单击上传图片按钮触发事件
		target : 事件源 jquery对象
		panel : 面板
		self ： 插件本身
	*/ 
	uploadFileBtn : function( target, panel, self ) {
		var staticAttr = self.staticAttr,
			settings = self.settings;
		panel.find("[name=" + staticAttr.uploadShowName+"]").show();
		panel.find("[name=" + staticAttr.urlShowName+"]").hide();
		panel.find("[name=" + staticAttr.urlFileBtn+"]").removeClass(settings.selectedClass);
		target.addClass(settings.selectedClass);
		return false;
	},
	/*
		单击添加url按钮触发事件 
		target : 事件源 jquery对象
		panel : 面板
		self ： 插件本身
	*/
	urlFileBtn : function( target, panel, self ) {
		var staticAttr = self.staticAttr,
			settings = self.settings;
		panel.find("[name=" + staticAttr.uploadShowName + "]").hide();
		panel.find("[name=" + staticAttr.urlShowName + "]").show();
		panel.find("[name=" + staticAttr.uploadFileBtn + "]").removeClass(settings.selectedClass);
		target.addClass(settings.selectedClass);
		return false;
	},
	ok : function( panel, self ) {
		/*
			这里只为了显示出按钮出来
		*/
	},
	onclose : function( panel, self ) {
		var staticAttr = self.staticAttr;
		staticAttr.uploadIsBusy = false;
	},
	/*
		确定插入图片
	*/
	uploadButton : function( target, panel, self ) {
		var staticAttr = self.staticAttr,
			settings = self.settings,
			//图片描述是否可以为空
			discription_can_null = settings.discription_can_null,
			//需要上传的文件
			obj = panel.find("[name="+staticAttr.inputFileName+"]"),
			//图片地址
			imgUrl = $.trim(panel.find("[name="+staticAttr.inputUrlName+"]").val()),
			//图片描述
			discription = $.trim(panel.find("[name="+staticAttr.imgDiscription+"]").val()),
			//图片地址校验正则
			reg = /^(http\:\/\/)[\w.\/-]+\.(jpg|jpeg|gif|png)/i , // /^(\w|\.|\/)+\.(jpg|jpeg|gif|png)$/i; 
			uploadFileBtn = panel.find("[name="+staticAttr.uploadFileBtn+"]"),
			//判断是上传图片还是添加url
			fig = uploadFileBtn.attr("class").indexOf(settings.selectedClass) > -1;
		//数据合法性校验
		if(fig && !self._checkFile(obj)) {
			self.error("提示：请选择一个有效的图片文件！");
			return false;
		}else if( !fig ) {
			if(imgUrl.length < 1) {
				self.error("url地址不能为空!");
				return false;
			}else if( !reg.test(imgUrl) ) {
				self.error("url地址格式有误!");
				return false;
			}
		}
		if( discription.length < 1 && !discription_can_null) {
			self.error("请填写图片描述，良好的描述可以帮助读者理解图片！");
			return false;
		}else if( discription.length > 500 ) {
			self.error("过多的图片描述可能会影响页面布局！");
			return false;
		}
		self._uploadFile();
		
		self.lock();
		setTimeout(function(){self.unlock()}, 10000);
	},
	//上传图片具体实现[内部调用方法]
	_uploadFile : function() {
		var self = E.plugin(HdImage),
			staticAttr = self.staticAttr,
			//iframe的id和name属性值
			iframefig = "articleUpload_iframe";
		if(staticAttr.uploadIsBusy) {
			self.error("请稍后...");
			return;
		}else {
			staticAttr.uploadIsBusy = true;
		}
		//iframe
		var iframe = '<iframe id="'+iframefig+'" name="'+iframefig+'" width="0" height="0"></iframe>';
		if(!$("#"+iframefig).length){
			$("body").append(iframe);
		}
		//提交
		self._uploadForm(iframefig);
	},
	//构造上传图片地址和form表单相关属性值
	_uploadForm : function( target ) {
		var self = E.plugin(HdImage),
			panel = self.panel,
			staticAttr = self.staticAttr,
			settings = self.settings,
			uploadFileBtn = panel.find("[name="+staticAttr.uploadFileBtn+"]"),
			//form表单
			form = panel.find("form"),
			//获取配置信息
			settings = self.settings,
			//form相关参数设置
			formAttrs = {"target" :target, "method" : "POST", "onsubmit" : "return true"},
			action = null,
			parms = null,
			formtype = 'enctype';
		//为了兼容不同版本jq对encoding兼容性处理不同，这里对IE6,7做特殊处理
		// 对于ie8+使用ie7标准的情况，需要使用document.documentMode来判断
		if($.browser.msie && ($.browser.version < 8 || document.documentMode ==7 )){
			formtype = 'encoding';
		}
		//选中的上传图片
		if(uploadFileBtn.hasClass(settings.selectedClass)) {
			action = settings.getFileAction();
			if(!action) {
				staticAttr.uploadIsBusy = false;
				return false;
			}
			//兼容不同版本的jquery，采用原生的设置
			form[0].setAttribute(formtype,'multipart/form-data');
		}else {
			action = settings.getUrlAction();
			if(!action) {
				staticAttr.uploadIsBusy = false;
				return false;
			}

			form[0].setAttribute(formtype,'application/x-www-form-urlencoded');
		}
		if(typeof action === 'string'){
			formAttrs['action'] = action;
		}else if(typeof action === 'object') {
			formAttrs['action'] = action.action;
			if(typeof action.postParms === 'object') {
				parms = action.postParms;
				for(var k in parms) {
					form.append('<input type="hidden" name="'+k+'" value="'+parms[k]+'">');
				}
			}
		}
		form.attr(formAttrs);
		//显示loading开始上传
		self.error("图片上传中....");
		//兼容不同版本的jquery在IE6,7下的不同表现，采用原生的设置
		form[0].submit();
	},
	
	
	// 插入内容
	// 在图片上传结束后，跳转的页面执行
	// 具体到小百科是 veiw/default/attachment_uploadimg.htm
	insert : function( img_src, img_link ) {
		var self = E.plugin(HdImage),
			data = {},
			Reference = E.plugin('Reference');
		
		// 获取插入图片面板上参考资料数据
		var panel = self.panel;
		//data.title = panel.find('input[name=title]').val();
		
		// 补充获取数据的代码...
		
		Reference.save(data, function(reference){
			self.loadImage(img_src, img_link, reference);
		});
	},
	
	// 加载图片
	loadImage : function( img_src, img_link, reference ) {
		var self = E.plugin(HdImage),
			panel = self.panel,
			staticAttr = self.staticAttr,
			img = new Image(),
			new_src = img_src,
			imgfig = panel.find("[name=" + staticAttr.imgSizeName+"]:checked").attr('imgsize');
		new_src = img_src.replace(/_140|_s|_950/i, imgfig);
		self.unlock();
		img.onload = function() {
			var title, align, width=parseInt(img.width), imgw=0;
			title = panel.find("[name=" + staticAttr.imgDiscription + "]").val();
			if (!title || title.length <1) {
				if($('#art_title').length){
					title = $('#art_title').val();
				}else if($('#_doc_title').length){
					title = $('#_doc_title').val();
				}else if($('#title').length){
					title = $('#title').val();
				}
			}
			if(width > self.config.max_width ) {
				imgw = self.config.max_width;
			}else {
				imgw = width;
			}
			align = panel.find("[name=" + staticAttr.imgAlignName + "]:checked").val();
			var html = '';
			var style = "width:" + imgw + "px;";
				if (align == 'left') {
					align = 'img_l';
				}else if(align == 'right') {
					align = 'img_r';
				}else {
					align = 'img_c';
					style = "width:" + imgw + "px;";
				}
				html = '<DIV class="img ' + align + '" style="' + style + '">';
				if (img_link) {
					html += '<A title="' + title + '" href="' + img_link + '" target=_blank>';
				}
				html += '<IMG title="' + title + '" alt="' + title + '"';
				//图片大小超过最大值max_width则给img标签加width属性
				if(width > self.config.max_width) {
					html += ' width="' + imgw + '"';
				}
				html += ' src="' + new_src + '"/>';
				if(img_link) {
					html += '</A>';
				}
				if(reference){
					title += '<sup class="refer" name="'+reference.name+'">'+reference.num+'</sup>'
				}
				html += '<STRONG>' + title + '</STRONG>' + '</DIV>';
			self.pasteHTML(html);
			self.hide();
			E.monitor(self.name);
			img.onload = function(){};
			staticAttr.uploadIsBusy = false;
			
			// ie下在段首插入图片时，会导致一个空p标签
			// 将其去除 2012-11-27 潘雪鹏
			if(Consts.IE){
				setTimeout(function(){
					var emptyP = E.$("img[src='"+new_src+"']").closest("div.img").prev("p");
					if( emptyP.text() == "" ){
						emptyP.remove();
					}
				}, 0);
			}
			E.plugin("DragImage").reset();
		};
		img.onerror = function() {
			self.error('提示：由于网络等原因导致图片插入失败！');
			staticAttr.uploadIsBusy = false;
		}
		img.src = new_src;
	},
	//obj表单数据校验
	_checkFile : function( obj ) {
		if(obj.val().length == 0) {
			return false;
		}
		if(! /\.(jpg|jpeg|gif|png)$/i.test(obj.val())) {
			return false;
		}
		return true;
	},
	
	resizeImageDivWidth: function(){
		resizeImageDivWidth();
	}
});

})(jQEditor);